<template>
  <div class="home" v-if="cur_word">
    <div class="img-body">
      <img :src="cur_word.images" alt />
    </div>

    <div class="btn-body">
      <button class="start" v-if="isStart===false" @click="start">开始</button>
      <template v-else>
        <button class="repeat" @click="playAudio">重复</button>
        <button class="next" @click="next">下一个</button>
      </template>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import axios from 'axios'
export default {
  name: 'HomeView',
  components: {
  },
  data () {
    return {
      index: 0,
      isStart: false,
      class_list: JSON.parse(window.localStorage.getItem('class_list')),
      all_word: JSON.parse(window.localStorage.getItem('all_word'))
    }
  },
  computed: {
    cur_class() {
      if (!this.$route.query.id) return null
      return this.class_list[this.$route.query.id]
    },
    cur_word() {
      if (!this.cur_class) return null
      const word_id = this.cur_class.word_ids[this.index]

      const cur_word = this.all_word.find(item => item.id === word_id)

      return cur_word
    }
  },
  async created () {
  },
  mounted() {
  },
  methods: {
    async addWordToReview () {
      await axios({
        method: 'put',
        url: process.env.VUE_APP_BASE_API + '/review/add_word?word_id=' + this.cur_word.id
      })
    },
    next () {
      if (this.index + 1 >= this.cur_class.word_ids.length) {
        alert('结束！！！！')
        this.$router.push('/home')
        return
      }
      this.index++
      this.playAudio()
      this.$nextTick(()=>{
        this.addWordToReview()
      })
    },
    playAudio () {
      this.$nextTick(() => {
        const audio = new Audio(this.cur_word.audioWord)
        audio.playbackRate = 0.8
        setTimeout(() => {
          audio.play()
          audio.addEventListener('ended', () => {
            this.playAudioTranslate()
          })
        }, 500)
      })
    },
    playAudioTranslate () {
      if (!this.cur_word || !this.cur_word.audioTranslate) return
      const audio = new Audio(this.cur_word.audioTranslate)
      audio.play()
    },
    start () {
      this.isStart = true
      this.addWordToReview()
      this.playAudio()
    }
  }
}
</script>
<style lang="less" scoped>
.img-body {
  width: 100%;
  height: 60vh;
  margin: 2vw 0;
  display: flex;
  justify-content: center;
  img {
    max-width: 100%;
    max-height: 100%;
  }
}
.btn-body {
  display: flex;
  justify-content: space-around;
  button {
    width: 15vw;
    height: 8vw;
    border-radius: 2vw;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 4vw;
    color: #fff;
  }
  .start {
    background-color: green;
  }
  .repeat {
    background-color: orange;
  }
  .next {
    background-color: green;
  }
  .give-up {
    background-color: #ccc;
  }
}
</style>
